/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * JDBCWindow.java
 *
 * Created on 23.11.2009, 10:48:55
 */

package at.nhmwien.schema_mapping_tool;

import java.sql.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

/**
 *
 * @author wkoller
 */
public class JDBCWindow extends javax.swing.JFrame {
    private DefaultComboBoxModel tableModel = null;
    private DefaultComboBoxModel driverModel = null;
    private DatabaseMetaData dbmd = null;
    private MainWindow mw = null;
    private int fieldType = -1;

    /** Creates new form JDBCWindow */
    public JDBCWindow() {
        initComponents();

        // Create our base table model
        this.tableModel = new DefaultComboBoxModel();
        this.tableList.setModel(tableModel);

        // Add a listener for the selection changed event of our list
        this.tableList.addListSelectionListener( new ListSelectionListener() {
            public void valueChanged( ListSelectionEvent evt ) {
                tableListSelectionChanged( evt );
            }
        });

        // Add all available JDBC drivers to our drop-down
        this.driverModel = new DefaultComboBoxModel();
        this.availDriversComboBox.setModel(this.driverModel);

        Enumeration<Driver> availDrivers = DriverManager.getDrivers();
        while( availDrivers.hasMoreElements() ) {
            this.driverModel.addElement(availDrivers.nextElement());
        }
    }

    public void display( MainWindow mw, int fieldType ) {
        this.setVisible(true);

        this.mw = mw;
        this.fieldType = fieldType;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        connectButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        tableList = new javax.swing.JList();
        readButton = new javax.swing.JButton();
        availDriversComboBox = new javax.swing.JComboBox();
        cancelButton = new javax.swing.JButton();
        jdbcURLLabel = new javax.swing.JLabel();
        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        dbnameLabel = new javax.swing.JLabel();
        jdbcURLTextField = new javax.swing.JTextField();
        usernameTextField = new javax.swing.JTextField();
        dbnameTextField = new javax.swing.JTextField();
        passwordField = new javax.swing.JPasswordField();

        setTitle("JDBC Schema Reading");
        setResizable(false);

        connectButton.setText("Connect");
        connectButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connectButtonActionPerformed(evt);
            }
        });

        tableList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableList.setLayoutOrientation(javax.swing.JList.VERTICAL_WRAP);
        tableList.setVisibleRowCount(30);
        jScrollPane2.setViewportView(tableList);

        readButton.setText("Read Schema");
        readButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                readButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        jdbcURLLabel.setText("Host-URL:");

        usernameLabel.setText("Username:");

        passwordLabel.setText("Password:");

        dbnameLabel.setText("Database:");

        jdbcURLTextField.setText("jdbc:type://host/");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jdbcURLLabel)
                    .addComponent(dbnameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dbnameTextField)
                    .addComponent(jdbcURLTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 212, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(usernameLabel)
                    .addComponent(passwordLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(passwordField, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 257, Short.MAX_VALUE))
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(10, Short.MAX_VALUE)
                .addComponent(cancelButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 421, Short.MAX_VALUE)
                .addComponent(readButton)
                .addGap(10, 10, 10))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(10, Short.MAX_VALUE)
                .addComponent(availDriversComboBox, 0, 504, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(connectButton)
                .addGap(10, 10, 10))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 583, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(connectButton)
                    .addComponent(availDriversComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jdbcURLLabel)
                    .addComponent(jdbcURLTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usernameLabel)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(dbnameLabel)
                    .addComponent(dbnameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(passwordLabel)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 490, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(readButton)
                    .addComponent(cancelButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void connectButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectButtonActionPerformed
        // TODO add your handling code here:
        try {
            Properties info = new Properties();
            info.setProperty( "user", this.usernameTextField.getText());
            info.setProperty("password", String.copyValueOf(this.passwordField.getPassword()));

            Connection conn = ((Driver) this.availDriversComboBox.getSelectedItem()).connect( this.jdbcURLTextField.getText() + this.dbnameTextField.getText(), info);

            //Connection conn = DriverManager.getConnection( "jdbc:mysql://192.168.56.101/koha?user=kohaadmin&password=koha" );
            this.dbmd = conn.getMetaData();

            String[] availTypes = new String[2];
            availTypes[0] = "TABLE";
            availTypes[1] = "VIEW";

            ResultSet rs = dbmd.getTables(null, null, null, availTypes);

            this.tableModel.removeAllElements();

            while( rs.next() ) {
                String tableName = rs.getString( "TABLE_NAME" );

                this.tableModel.addElement(tableName);

                //this.debugTextArea.setText( this.debugTextArea.getText() + tableName + "\n");
            }
        }
        catch ( Exception e ) {
            e.printStackTrace();
        }

    }//GEN-LAST:event_connectButtonActionPerformed

    private void readButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_readButtonActionPerformed
        // TODO add your handling code here:
        if( this.mw != null ) {
            if( tableList.getSelectedValue() != null ) {
                String tableName = (String) tableList.getSelectedValue();

                LinkedHashMap<String,LinkedHashMap> fields = new LinkedHashMap<String,LinkedHashMap>();

                try {
                    ResultSet cols = this.dbmd.getColumns(null, null, tableName, null);

                    while (cols.next()) {
                        String columnName = cols.getString("COLUMN_NAME");

                        LinkedHashMap fieldInfo = new LinkedHashMap();
                        fieldInfo.put( "name", columnName );
                        fieldInfo.put( "subfields", null );

                        fields.put( columnName, fieldInfo );

                    }

                    this.mw.handleFields( this.fieldType, fields );

                    // Close DB connection
                    this.dbmd.getConnection().close();
                    // Hide window
                    this.setVisible(false);

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }//GEN-LAST:event_readButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void tableListSelectionChanged( ListSelectionEvent evt ) {
        if( !evt.getValueIsAdjusting() ) {
            String tableName = (String) tableList.getSelectedValue();

            try {
                ResultSet cols = this.dbmd.getColumns(null, null, tableName, null);

                while( cols.next() ) {
                    String columnName = cols.getString( "COLUMN_NAME" );
                }
            }
            catch( Exception e ) {
                e.printStackTrace();
            }
        }
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox availDriversComboBox;
    private javax.swing.JButton cancelButton;
    private javax.swing.JButton connectButton;
    private javax.swing.JLabel dbnameLabel;
    private javax.swing.JTextField dbnameTextField;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel jdbcURLLabel;
    private javax.swing.JTextField jdbcURLTextField;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JButton readButton;
    private javax.swing.JList tableList;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JTextField usernameTextField;
    // End of variables declaration//GEN-END:variables

}
